package reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * Created with IntelliJ IDEA
 * Description:通过反射创建对象学习
 * User:22954
 * Date:2024-04-17
 * Time:14:08
 */
public class ReflecCreateInstance {
    /*
    setAccessible(boolean flag)  flag = true----暴破-暴力破解 可通过反射访问任意属性修饰的构造器/方法/属性 相当于后门
     */
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> cls = Class.forName("reflection.User");

        Object o1 = cls.getDeclaredConstructor().newInstance();
        System.out.println(o1);//User{name='Jack', age=10}

        Object o2 = cls.getDeclaredConstructor(String.class).newInstance("John");
        System.out.println(o2);//User{name='John', age=10}

        Constructor<?> constructor = cls.getDeclaredConstructor(String.class, int.class);
        constructor.setAccessible(true);
        Object o3 = constructor.newInstance("Bob", 30);
        System.out.println(o3);//User{name='Bob', age=30}
    }
}

class User {
    private String name;
    private int age;
    private static String id;

    public User() {
        name = "Jack";
        age = 10;
    }

    public User(String name) {
        this.name = name;
        age = 10;
    }

    private User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void hi() {
        System.out.println("hi");
    }

    public void hi(String name) {
        System.out.println("hi " + name);
    }

    private static String sentence(int n, String s, char c) {
        return n + " " + s + " " + c;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}